package com.tjmntv.tj.myapplication.demo6

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MyService : LifecycleService() {
    private var number = 0
    val numberLiveData: MutableLiveData<Int> = MutableLiveData(0)
    override fun onCreate() {
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        lifecycleScope.launch {
            while (true) {
                delay(1_000)
                Log.e("@@@", "onStartCommand: ${number++}");
            }
        }
        return super.onStartCommand(intent, flags, startId)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    inner class MyBinder : Binder() {
        val service: MyService = this@MyService
    }

    override fun onBind(intent: Intent): IBinder? {
        super.onBind(intent)
        lifecycleScope.launch {
            while (true) {
                delay(1000)
                numberLiveData.value = numberLiveData.value?.plus(1)
            }
        }
        return MyBinder()
    }

    override fun getLifecycle(): Lifecycle {
        return super.getLifecycle()
    }
}